package com.zgq.share.thirdplatform.renren;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.zgq.share.thirdplatform.BasicAdapter;
import com.zgq.share.thirdplatform.IPlatform;
import com.zgq.share.thirdplatform.PlatformDefs;
import com.zgq.share.thirdplatform.Session;
import com.zgq.share.ui.WebViewActivity;

/**
 * 人人网新鲜事分享适配器
 * @author Administrator
 *
 */
public class RenrenAdapter extends BasicAdapter implements IPlatform {

	HttpURLConnection httpurlconnection = null;
	Session s;
	
	public RenrenAdapter(Context context) {
		super(context);
	}

	@Override
	public boolean supportLocation() {
		return false;
	}

	@Override
	public boolean supportImage() {
		return false;
	}

	@Override
	public boolean authenticate() {
		try {
			String renren_url = PlatformDefs.RENREN_AUTHORIZE_URL +
			"client_id=" + PlatformDefs.RENREN_API_KEY + "&response_type=code"+
			"&display=touch&redirect_uri=" + PlatformDefs.RENREN_REDIRECT_URI +
			"&scope=" + PlatformDefs.RENREN_OAUTH_SCOPE; 
			Intent intent = new Intent();
			Bundle bundle = new Bundle();
			bundle.putString("uri", renren_url);
			intent.putExtras(bundle);
			intent.setClass(context, WebViewActivity.class);
			context.startActivity(intent);
			
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public Session parseAuthResult(Intent intent) {
		s = new Session();
		try {
			URL url = new URL(PlatformDefs.RENREN_TOKEN_URL);

			httpurlconnection = (HttpURLConnection) url.openConnection();
			httpurlconnection.setDoOutput(true);
			httpurlconnection.setRequestMethod("POST");
			String grant_type = "grant_type=authorization_code";
			String code = "&code=" + PlatformDefs.code;
			String client_id = "&client_id=" + PlatformDefs.RENREN_API_KEY;
 			String client_secret = "&client_secret=" + PlatformDefs.RENREN_SECRET;
			String redirect_uri = "&redirect_uri=" + PlatformDefs.RENREN_REDIRECT_URI;
			httpurlconnection.getOutputStream().write(
					(grant_type + code + client_id + client_secret + redirect_uri).getBytes());

			httpurlconnection.getOutputStream().flush();
			httpurlconnection.getOutputStream().close();
			int statusCode = httpurlconnection.getResponseCode();

			// 状态码返回200代表成功
			if (statusCode == 200) {
				try {
					InputStream is = httpurlconnection.getInputStream();
					Reader reader = new BufferedReader(new InputStreamReader(is), 4000);
					StringBuilder buffer = new StringBuilder();
					try {
						char[] tmp = new char[1024];
						int l;
						while ((l = reader.read(tmp)) != -1) {
							buffer.append(tmp, 0, l);
						}
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						reader.close();
					}
					String string = buffer.toString();
					JSONObject jb = new JSONObject(string);
					/*access_token = jb.getString("access_token");
					expires_in = jb.getString("expires_in");
					refresh_token = jb.getString("refresh_token");*/
					s.setAccess_token(jb.getString("access_token"));
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (httpurlconnection != null)
						httpurlconnection.disconnect();
				}
			}
			getSessionKey();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		return s;
	}

	/*@Override
	public boolean send(String title, String message, GeoPointEx point) {
		// TODO Auto-generated method stub
		return false;
	}*/

	@Override
	public boolean validate() {
		// TODO Auto-generated method stub
		return false;
	}

	/**
	 * 获取授权认证的SessionKey值
	 */
	public void getSessionKey() {
		try {
			URL url = new URL(PlatformDefs.RENREN_SESSION_URL);

			httpurlconnection = (HttpURLConnection) url.openConnection();
			httpurlconnection.setDoOutput(true);
			httpurlconnection.setRequestMethod(PlatformDefs.RENREN_METHOD_TYPE);
			String param1 = "oauth_token=" + s.getAccess_token();

			httpurlconnection.getOutputStream().write(param1.getBytes());
			httpurlconnection.getOutputStream().flush();
			httpurlconnection.getOutputStream().close();
			int statusCode = httpurlconnection.getResponseCode();

			// 状态码返回200代表成功
			if (statusCode == 200) {
				try {
					InputStream is = httpurlconnection.getInputStream();
					Reader reader = new BufferedReader(
							new InputStreamReader(is), 4000);
					StringBuilder buffer = new StringBuilder();
					try {
						char[] tmp = new char[1024];
						int l;
						while ((l = reader.read(tmp)) != -1) {
							buffer.append(tmp, 0, l);
						}
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						reader.close();
					}
					String string = buffer.toString();
					JSONObject value = new JSONObject(string);
					// 先获取数组中的三个大的选项
					String renrenToken = value.getString("renren_token");
					/*String oauth_token = value.getString("oauth_token");*/
					String userToken = value.getString("user");
					// 解析第一个renren_token,并获取其中的三个值
					JSONObject renren_token = new JSONObject(renrenToken);
					String session_key = renren_token.getString("session_key");
					/*String expires_in = renren_token.getString("expires_in");
					String session_secret = renren_token.getString("session_secret");*/
                    //  第三个，并获取userId
					JSONObject user = new JSONObject(userToken);
					String userId = user.getString("id");
					
					s.setUid(userId);
					s.setKey(session_key);
				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (httpurlconnection != null) {
				httpurlconnection.disconnect();
			}
		}
	}

	@Override
	public Bundle setBundle() {
		
		return null;
	}
}
